import { TokenKey, getCookie, removeCookie, setCookie } from "@/utils/cache"
import { requestToken } from "@/api/user/user"

export interface UserInfo {
  name: string
}
export const userInfokey = 'user_Info'

export const defaultUserInfo: UserInfo = {
  name: 'guest'
}
export const redirectLogin = () => {
  removeCookie(TokenKey);
  location.href = import.meta.env.LOGIN_URL + '/login?redirect=' + encodeURIComponent(location.href);
}

export const getToken = async () => {
  const token = getCookie(TokenKey);
  if (token) return token;
  const [href, queryStr] = location.href.split("?")
  if (!queryStr) {
    redirectLogin();
    return;
  }
  interface Query {
    access_token_code: string;
  }
  const queryObj = {} as Query
  const queryList = queryStr.split("&")
  queryList.forEach(item => {
    const [key, val] = item.split("=")
    queryObj[key as keyof Query] = val;
  })
  if (!queryObj.access_token_code) {
    redirectLogin();
    return;
  }
  const access_token: any = await requestToken(queryObj.access_token_code);
  if (!access_token) {
    redirectLogin();
    return;
  }

  setCookie(TokenKey, access_token)
  return access_token;

}